<?php


namespace app\api\controller;

use app\admin\library\Auth;
use app\api\model\Anchor_config;
use app\api\model\Notice;
use app\api\model\Order_news;
use app\common\model\Anchor_custorm;
use app\common\model\MoneyLog;
use think\Db;

use app\common\controller\Api;
use think\Exception;
use think\exception\PDOException;
use think\Queue;

/*
 * 主播接口
 */

class Anchor extends Api
{

    protected $noNeedLogin = [];
    protected $noNeedRight = ["*"];

    //主播主页详细信息
    public function anchor_detail()
    {
        $id = $this->request->post('id');
        $user = $this->auth->getUser();
        //主播信息
        $anchor_user = Db::name('user')
            ->where(['id' => $id, 'group_id' => 1])
            ->field('id,group_id,nickname,board_switch,exit_switch,up_switch,anchor_status,order_ing,avatar,gender')
            ->find();
        if (empty($anchor_user)) {
            $this->error('主播不存在');
        }
        $anchor_user['config'] = Db::name('anchor_config')
            ->where('anchor_id', $anchor_user['id'])->find();
        $order = [];
        //查询我待服务订单
        $order_dai = Db::name('order_place')->where('status',0)->where('anchor_id',$anchor_user['id'])->find();
        if ($anchor_user['anchor_status'] == 1 && $anchor_user['order_ing'] != 0) {
            //主播开播并且正在进行订单信息
            $order_pro = Db::name('order_place_pro')->where('id', $anchor_user['order_ing'])->find();
            $order = Db::name('order_place')->where('id', $order_pro['order_id'])->find();
            $order['createtime'] = date("Y-m-d H:i:s", $order['createtime']);
            $order['user_nickname'] = Db::name('user')->where('id', $order['user_id'])->value('nickname');
            $order['user_avatar'] = Db::name('user')->where('id', $order['user_id'])->value('avatar');
            $order['custom'] = $order_pro['custom'];
        }else{
            if($user['group_id'] == 1){
                if ($order_dai){
                    $order = $order_dai;
                    $order['createtime'] = date("Y-m-d H:i:s", $order_dai['createtime']);
                    $order['user_nickname'] = Db::name('user')->where('id', $order_dai['user_id'])->value('nickname');
                    $order['user_avatar'] = Db::name('user')->where('id', $order_dai['user_id'])->value('avatar');
                    $order['custom'] = 0;
                }else{
                    $order = [];
                }
            }else{
                $order = [];
            }

        }

        $user = $this->auth->getUser();
        //是否有上车单子
        $myorder_gen = Db::name('order_gen')
            ->where('user_id', $user['id'])
            ->where('orderpro_id', $anchor_user['order_ing'])
            ->where('status', 0)
            ->find();
        if($myorder_gen){
            $order['is_gen'] = 1;
            $order['remain_num'] = $myorder_gen['remain_num'];
            $order['gen_order_id'] = $myorder_gen['id'];
        }else{
            $order['is_gen'] = 0;
        }
        $is_follow = Db::name('user_follow')
            ->where('r_user_id',$user['id'])
            ->where('l_user_id',$anchor_user['id'])
            ->where('status',1)
            ->where('genre',1)->find();
        if($is_follow){
            $anchor_user['is_follow'] = 1;
        }else{
            $anchor_user['is_follow'] = 0;
        }
        $date = [
            'anchor_user' => $anchor_user,
            'order' => $order
        ];
        $this->success('成功', $date);


    }

    //主播详情排行榜
    public function anchor_top()
    {
        $id = $this->request->post('id');
        $pagesize = $this->request->post('pagesize', 10);
        $status = $this->request->post('status');
        //主播信息
        $anchor_user = Db::name('user')
            ->where(['id' => $id, 'group_id' => 1])
            ->field('id,group_id,nickname,board_switch,exit_switch,up_switch,anchor_status,order_ing,avatar,gender')
            ->find();
        if (empty($anchor_user)) {
            $this->error('主播不存在');
        }
        if ($status == 1) {
            //主播的下单榜
            $data = Db::name('order_place')
                ->where('status', 0)
                ->where('anchor_id', $id)
                ->group('user_id')
                ->field('id,createtime,user_id,sum(num) as num')
                ->order('num desc,createtime asc')
                ->paginate($pagesize)->each(function ($orderdate) {
                    $orderdate['createtime'] = date("Y-m-d H:i:s", $orderdate['createtime']);
//                    $orderdate['num'] = $orderdate['sum(num)'];
                    $orderdate['nickname'] = Db::name('user')->where('id', $orderdate['user_id'])->value('nickname');
                    $orderdate['avatar'] = Db::name('user')->where('id', $orderdate['user_id'])->value('avatar');
                    return $orderdate;
                });
        } elseif ($status == 2) {
            //主播的上车榜
            $data = Db::name('order_gen')
                ->where('status', 0)
                ->where('anchor_id', $id)
                ->where('orderpro_id', $anchor_user['order_ing'])
                ->group('user_id')
                ->field('id,createtime,user_id,sum(remain_num) as num')
                ->order('num desc,createtime asc')
                ->paginate($pagesize)->each(function ($orderdate) {
                    $orderdate['createtime'] = date("Y-m-d H:i:s", $orderdate['createtime']);
//                    $orderdate['num'] = $orderdate['sum(num)'];
                    $orderdate['nickname'] = Db::name('user')->where('id', $orderdate['user_id'])->value('nickname');
                    $orderdate['avatar'] = Db::name('user')->where('id', $orderdate['user_id'])->value('avatar');
                    return $orderdate;
                });
        } elseif ($status == 3) {
            //主播的守护榜
            $data = Db::name('top')
                ->where('anchor_id', $id)
                ->field('id,user_id,anchor_id,acc_score,updatetime')
                ->order('acc_score desc,updatetime desc')
                ->paginate($pagesize)->each(function ($orderdate) {
                    $orderdate['createtime'] = date("Y-m-d H:i:s", $orderdate['updatetime']);
                    $orderdate['nickname'] = Db::name('user')->where('id', $orderdate['user_id'])->value('nickname');
                    $orderdate['avatar'] = Db::name('user')->where('id', $orderdate['user_id'])->value('avatar');
                    return $orderdate;
                });
        }
        $this->success('成功', $data);
    }

    //主播开始服务
    public function order_start()
    {
        $order_id = $this->request->post('id');
        $user = $this->auth->getUser();
        $order = Db::name('order_place')->where('id', $order_id)->where('status', 0)->find();
        if (!$order) {
            $this->error('此订单有误,请刷新重试');
        }
        if ($user['group_id'] == 0) {
            $this->error('您不是主播,无权限');
        }
        if ($user['up_switch'] == 0) {
            $this->error('请打开上播按钮才能开启服务');
        }
        if($user['anchor_status'] !=0){
            $this->error('请完成正在进行中的订单才能进行下一单');
        }

        Db::startTrans();
        try {
            //拿最近的待服务小单数据
            $order_pro = Db::name('order_place_pro')->where('order_id', $order_id)->where('status', 0)->find();
            if ($order_pro) {
                //修改订单和订单pro
                Db::name('order_place')->where('id', $order_id)->update([
                    'alr_num' => $order['alr_num'] + 1,
                    'status' => 1,
                    'begin_time' => time()
                ]);
                Db::name('order_place_pro')->where('id', $order_pro['id'])->update([
//                    'custom' => 0,
                    'status' => 1,
                    'begin_time' => time(),
                ]);
                //修改主播当前信息
                Db::name('user')->where('id', $user['id'])->update([
                    'anchor_status' => 1,
                    'order_ing' => $order_pro['id'],
                ]);

                //开启服务订单消息
                $content = "主播开启服务了你的订单";
                Order_news::new_add($order_pro['user_id'], $order['id'], $order_pro['order_sn'], 1, 0, $content);

                //微信小程序订阅通知
                $id_user = Db::name('user')->where('id',$order['user_id'])->find();
                if (isset($id_user) && $id_user['order_begin_notice'] == 1) {
                    //发订阅消息
                    $newsdata = [
                        'character_string1' => [
                            'value' => $order['order_sn'],
                        ],
                        'phrase2' => [
                            'value' =>"进行中",
                        ],
                        'thing7' => [
                            'value' => "下单服务",
                        ],
                        'thing10' => [
                            'value' => $content,
                        ],
                    ];
                    Queue::push('app\common\job\Subscribe@sub', ['user_id' => $order['user_id'], 'newsdata' => $newsdata, 'encode' => "gpinVnVsWeB2_UJo3lWfvkStXCsWqjPauoWxEFwPVzU", 'content' => "order_begin_notice"], 'sub');
                }
            }
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage(), $e->getTrace());
        }
        $this->success('开始成功');
    }

    //主播开播、关播
    public function up_anchor()
    {
        $user = $this->auth->getUser();
        $up_switch = $this->request->post('up_switch');
        if ($up_switch == 0) {
            $update = Db::name('user')->where('id', $user['id'])->update(['up_switch' => 1]);
            if ($update) {
                try {
                    //通知关注我的用户
                    $ids = Db::name('user_follow')->where('l_user_id', $user['id'])->where('status',1)->where('genre',1)->column('r_user_id');
                    $anchor_nickname = $user['nickname'];
                    foreach ($ids as $k => $v) {
                        $content = "您关注的主播“" . "$anchor_nickname" . "” 开播了，快来围观";
                        $notice = new Notice();
                        $notice->user_id = $v;
                        $notice->content = $content;
                        $notice->title   = $content;
                        $notice->save();
                        //微信小程序订阅通知
                        $id_user = Db::name('user')->where('id',$v)->find();
                        if (isset($id_user) && $id_user['up_notice'] == 1) {
                            //发订阅消息
                            $newsdata = [
                                'thing1' => [
                                    'value' => $anchor_nickname,
                                ],
                                'time3' => [
                                    'value' =>date("Y-m-d H:i:s", time()),
                                ],
                                'thing4' => [
                                    'value' => $content,
                                ],
                            ];
                            Queue::push('app\common\job\Subscribe@sub', ['user_id' => $v, 'newsdata' => $newsdata, 'encode' => "pSiGXnoq50eywGQ1LPiDbP4Osq_RXalC7gY2EfVE1GI", 'content' => "up_notice"], 'sub');
                        }
                    }

                } catch (PDOException $exception) {
                    $msg = $exception->getMessage();
                    if (preg_match("/.+Integrity constraint violation: 1062 Duplicate entry '(.+)' for key '(.+)'/is", $msg, $matches)) {
                        $msg = "导入失败，包含【{$matches[1]}】的记录已存在";
                    };
                    $this->error($msg);
                } catch (Exception $e) {
                    $this->error($e->getMessage());
                }
                $this->success('开启成功');
            }
        } elseif ($up_switch == 1) {
            if($user['anchor_status'] != 0 ){
                $this->error('请先完成正在进行的订单');
            }
            $update = Db::name('user')->where('id', $user['id'])->update(['up_switch' => 0]);
            $this->success('关闭成功');
        }
    }

    //主播开启/关闭上车
    public function board_anchor()
    {
        $user = $this->auth->getUser();
        $board_switch = $this->request->post('board_switch');
        if ($board_switch == 0) {
            if($user['anchor_status'] == 1) {
                $out_board = Db::name('order_place_pro')->where('id',$user['order_ing'])->value('out_board');
                if($out_board == 1){
                    $this->error('此单已经开启过上车按钮了，不能再开上车了');
                }
            }
            $update = Db::name('user')->where('id', $user['id'])->update(['board_switch' => 1]);
            if ($update) {
                $this->success('开启成功');
            }
        } elseif ($board_switch == 1) {
            $update = Db::name('user')->where('id', $user['id'])->update(['board_switch' => 0]);
            if ($update) {
                $this->success('关闭成功');
            }
        }

    }

    //主播查询此关卡奖励
    public function anchor_custorm()
    {
        $user = $this->auth->getUser();
        $custom = $this->request->post('custom');
        $anchor_custorm = Db::name('anchor_custorm')->where('anchor_id', $user['id'])->where('custom', $custom)->find();
        $this->success('成功', $anchor_custorm);
    }

    //主播开启/关闭下车
    public function exit_anchor()
    {
        $user = $this->auth->getUser();
        $exit_switch = $this->request->post('exit_switch');
        if ($exit_switch == 0) {  //开启下车
            //下车时输入的关卡
            $update = Db::name('user')->where('id', $user['id'])->update(['exit_switch' => 1]);
            if ($update != false) {
                //给参与当前订单的人发通知
                if($user['order_ing'] != 0 ){
                    $order_pro = Db::name('order_place_pro')->where('id',$user['order_ing'])->find();
                    $user_gen = Db::name('order_gen')->where('order_id',$order_pro['order_id'])->where('status',0)->column('user_id');
                    $ids = array_merge([$order_pro['user_id'],$user_gen]);
                    //去空并且重组
                    $ids =array_values(array_filter($ids));
                    $anchor_nickname = $user['nickname'];
                    foreach ($ids as $k => $v) {
                        $content = "您关注的主播“" . "$anchor_nickname" . "” 开启了下车";
                        $notice = new Notice();
                        $notice->user_id = $v;
                        $notice->content = $content;
                        $notice->title   = $content;
                        $notice->save();
                    }
                }
                $this->success('开启成功');
            }
        } elseif ($exit_switch == 1) { //关闭下车
            try {
                $update = Db::name('user')->where('id', $user['id'])->update(['exit_switch' => 0]);
                if ($user['order_ing']){
                    Db::name('order_place_pro')->where('id',$user['order_ing'])->update(['custom'=>0]);
                }
            }catch (Exception $e) {
                $this->error($e->getMessage());
            }
            if ($update != false) {
                $this->success('关闭成功');
            }
        }
    }

    //用户  查看我的上车单子信息
    public function myorder_gen()
    {
        $id = $this->request->post('id');
        $user = $this->auth->getUser();
        $myorder_gen = Db::name('order_gen')
            ->where('user_id', $user['id'])
            ->where('order_id', $id)
            ->where('status', 0)
            ->find();
//        $gen_user_id = Db::name('order_gen')->where('order_id', $myorder_gen['order_id'])->value('user_id');
        $gen_user = Db::name('user')->where('id', $myorder_gen['user_id'])->find();

        $place_user_id = Db::name('order_place')->where('id', $myorder_gen['order_id'])->value('user_id');
        $place_user = Db::name('user')->where('id', $place_user_id)->find();

        if ($myorder_gen) {
            $myorder_gen['nickname_gen'] = $gen_user['nickname'];
            if ($user['avatar']) {
                $myorder_gen['avatar_gen'] = $gen_user['avatar'];
            } else {
                $myorder_gen['avatar_gen'] = '';
            }
            $myorder_gen['nickname_place'] = $place_user['nickname'];
            if ($user['avatar']) {
                $myorder_gen['avatar_place'] = $place_user['avatar'];
            } else {
                $myorder_gen['avatar_place'] = '';
            }
            $myorder_gen['nickname_anchor'] = Db::name('user')->where('id', $myorder_gen['anchor_id'])->value('nickname');
            $myorder_gen['avatar_anchor'] = Db::name('user')->where('id', $myorder_gen['anchor_id'])->value('avatar');
            $myorder_gen['createtime'] = date("Y-m-d H:i:s", $myorder_gen['createtime']);
            $this->success('成功', $myorder_gen);
        } else {
            $this->error('没有上车信息');
        }

    }

    //主播更新关数（下单结算按钮 4.11改动  结算）
    public function change_custom()
    {
        $custom = $this->request->post('custom');
        if($custom< 0 || $custom>10){
            $this->error('选择关卡数不正确');
        }
        $user = $this->auth->getUser();
        //正在进行的小单
        $order_pro_ing = Db::name('order_place_pro')->where('id', $user['order_ing'])->where('status', 1)->find();
        //正在进行的下单订单
        $place_user = Db::name('order_place')->where('id', $order_pro_ing['order_id'])->where('status', 1)->find();

        if (!$place_user || !$order_pro_ing) {
            $this->error('订单有误');
        }
        $update1 = Db::name('order_place_pro')->where('id', $user['order_ing'])->where('status', 1)->update(['custom' => $custom]);
//        //本次结算本关奖励
//        $anchor_custom = Db::name('anchor_custorm')->where('anchor_id', $place_user['anchor_id'])->where('custom',$custom)->find();
//        //是否有跟此小单的跟车用户
//        $order_gens = Db::name('order_gen')->where('orderpro_id', $order_pro_ing['id'])->where('status', 0)->select();
//        Db::startTrans();
//        try {
//            //记录本次结算关数记录
//            $update1 = Db::name('order_place_pro')->where('id', $user['order_ing'])->where('status', 1)->update(['custom' => $custom]);
//            //上车所有用户本关结算
//            if ($order_gens) {
//                foreach ($order_gens as $k => $v) {
//                    $custom_gen_guard =  $anchor_custom['gen_guard'] * $v['remain_num'];
//                    $this->gen_custom($v['user_id'], $v['id'],$custom_gen_guard,$custom);
//                }
//            }
//            //结算下单的用户
//            $custom_place_guard =  $anchor_custom['place_guard'] ;
//            $this->place_custom($place_user['user_id'], $place_user['id'],$order_pro_ing['id'],$custom_place_guard,$custom);
//            Db::commit();
//        } catch (Exception $e) {
//            Db::rollback();
//            $this->error($e->getMessage(), $e->getTrace());
//        }
        $this->success('成功');
    }

//    //上车关卡结算  （4.11）
//    public function  gen_custom($user_id,$id,$custom_gen_guard,$custom){
//        $gen_order = Db::name('order_gen')->where('id',$id)->find();
//        //记录上车订单变化
//        Db::name('order_gen')->where('id', $id)->update([
//            'gen_guard' => $gen_order['gen_guard'] + $custom_gen_guard,
//            'updatetime' => time()
//        ]);
//        \app\common\model\User::score($custom_gen_guard, $user_id, 2, $id, $gen_order['anchor_id'], $custom);
//    }
//    //下单关卡结算  （4.11）
//    public function  place_custom($user_id,$id,$order_pro_id,$custom_place_guard,$custom){
//        $place_user = Db::name('order_place')->where('id',$id)->find();
//        //记录下单订单变化
//        Db::name('order_place')->where('id', $id)->update([
//            'place_guard' => $place_user['place_guard'] + $custom_place_guard,
//            'updatetime' => time()
//        ]);
//        //小单子订单变化
//        $order_pro_ing = Db::name('order_place_pro')->where('id',$order_pro_id)->find();
//        Db::name('order_place_pro')->where('id',$order_pro_id)->where('status', 1)->update([
//            'place_guard' => $order_pro_ing['place_guard'] + $custom_place_guard,
//            'end_time' => time()
//        ]);
//        \app\common\model\User::score($custom_place_guard, $user_id, 1, $order_pro_id, $place_user['anchor_id'], $custom);
//    }

    //用户（跟车） 点击下车
    public function exit_usergen()
    {
        $user = $this->auth->getUser();
        $user_id = $user['id'];
        $id = $this->request->post('id');
        $set_num = $this->request->post('set_num', 0);

        if($set_num < 1){
            $this->error('下车单数不能小于1');
        }

        $gen_user = Db::name('order_gen')->where('id', $id)->where('status', 0)->find();
        if(!$gen_user){
            $this->error('订单有误');
        }
        //主播信息
        $anchor_user = Db::name('user')
            ->where(['id' => $gen_user['anchor_id'], 'group_id' => 1])
            ->field('id,group_id,nickname,board_switch,exit_switch,up_switch,anchor_status,order_ing,avatar,gender')
            ->find();
        if ($anchor_user['exit_switch'] == 0) {
            $this->error('主播未开启下车按钮不能下车');
        }
        $return = $this->user_exit($user_id, $id, $set_num);
        //弹窗内容
        $order = Db::name('order_gen')->where('id',$id)->find();
        //正在进行的小单信息
        $order_pro_ing = Db::name('order_place_pro')->where('id', $order['orderpro_id'])->find();
        //结算奖励计算
        $anchor_custom = Db::name('anchor_custorm')->where('anchor_id', $gen_user['anchor_id'])->where('custom',$order_pro_ing['custom'])->find();
        $score = $anchor_custom['gen_guard'] * $set_num;
        $order['score_ing'] = $score;
        if ($return) {
            $this->success('下车成功',$order);
        }

    }

    //用户（上车） 点击下车 (共用public)
    public function user_exit($user_id, $id, $set_num)
    {
        $gen_user = Db::name('order_gen')->where('id', $id)->where('status', 0)->find();
        if ($set_num > $gen_user['remain_num']) {
            $this->error('已超过剩余单数');
        }
        if ($gen_user['remain_num'] <= 1) {
            $set_num = $gen_user['remain_num'];
        }
        //正在进行的小单信息
        $order_pro_ing = Db::name('order_place_pro')->where('id', $gen_user['orderpro_id'])->where('status', 1)->find();
        $custom_ing = $order_pro_ing['custom'];
        //主播信息
        $anchor_user = Db::name('user')
            ->where(['id' => $gen_user['anchor_id'], 'group_id' => 1])
            ->field('id,group_id,nickname,board_switch,exit_switch,up_switch,anchor_status,order_ing,avatar,gender')
            ->find();


        //结算奖励计算
        $anchor_custom = Db::name('anchor_custorm')->where('anchor_id', $gen_user['anchor_id'])->where('custom',$custom_ing)->find();
        $score = $anchor_custom['gen_guard'] * $set_num;

        $new_remain_num = $gen_user['remain_num'] - $set_num;
//        var_dump($score);die;
        Db::startTrans();
        try {
            if ($new_remain_num > 0) {  //还有剩下的倍数
                //记录上车单子订单变化
                Db::name('order_gen')->where('id', $id)->update([
                    'exit_custom' => $custom_ing,
                    'alr_num' => $gen_user['alr_num'] + $set_num,
                    'remain_num' => $new_remain_num,
                    'gen_guard' => $gen_user['gen_guard'] + $score,
                    'updatetime' => time()
                ]);
                //用户的守护值变化
                $data = [
//                    'custom_start' => $gen_user['board_custom'],
                    'custom_ing' => $custom_ing,
                    'num_ing' => $set_num,
                    'num_remain' => $new_remain_num,
                    'total_num' => $gen_user['num']
                ];
                \app\common\model\User::score($score, $user_id, 2, $id, $gen_user['anchor_id'], $data);
                //主播金币变化上车单子结算
                \app\common\model\User::money($set_num * $gen_user['price'] , $gen_user['anchor_id'], 4, $id);
            } else {  //已经无倍数  完成此上车订单
                //记录上车订单变化
                Db::name('order_gen')->where('id', $id)->update([
//                    'exit_custom' => $custom_ing,
                    'end_exit_custom' => $custom_ing,
                    'alr_num' => $gen_user['alr_num'] + $set_num,
                    'remain_num' => $new_remain_num,
                    'gen_guard' => $gen_user['gen_guard'] + $score,
                    'status' => 1,
                    'updatetime' => time(),
                    'end_time' => time(),
                ]);
                //订单完成消息
                $content = "您的上车订单已完成,感谢支持";
                Order_news::new_add($gen_user['user_id'], $gen_user['id'], $gen_user['order_sn'], 2, 0, $content);
                //用户的守护值变化
                $data = [
//                    'custom_start' => $gen_user['board_custom'],
                    'custom_ing' => $custom_ing,
                    'num_ing' => $set_num,
                    'num_remain' => $new_remain_num,
                    'total_num' => $gen_user['num']
                ];
                \app\common\model\User::score($score, $user_id, 2, $id, $gen_user['anchor_id'], $data);
                //主播金币变化上车单子结算
                \app\common\model\User::money($set_num * $gen_user['price'] , $gen_user['anchor_id'], 4, $id);
                //订单完成消息
                $content = "您的上车订单已完成,感谢支持";
                Order_news::new_add($gen_user['anchor_id'], $gen_user['id'], $gen_user['order_sn'], 2, 1, $content);
            }
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage(), $e->getTrace());
        }
        return true;
    }


    //用户（下单的人）点击下车
//    public function exit_userplace()
//    {
//        $user = $this->auth->getUser();
//        $user_id = $user['id'];
//        $id = $this->request->post('id');
//        $place_user = Db::name('order_place')->where('id', $id)->where('status', 1)->find();
//
//        //主播信息
//        $anchor_user = Db::name('user')
//            ->where(['id' => $place_user['anchor_id'], 'group_id' => 1])
//            ->field('id,group_id,nickname,board_switch,exit_switch,up_switch,anchor_status,order_ing,avatar,gender')
//            ->find();
//        //正在进行的小单信息
//        $order_pro_ing = Db::name('order_place_pro')->where('id', $anchor_user['order_ing'])->where('status', 1)->find();
//        if (!$place_user || !$order_pro_ing) {
//            $this->error('订单有误');
//        }
//        if ($anchor_user['exit_switch'] == 0) {
//            $this->error('主播未开启下车按钮不能下车');
//        }
//
//        //是否此大单还有小单
//        $remain_order_pro = Db::name('order_place_pro')->where('order_id', $id)->where('status', 0)->field('id,place_price')->select();
//        //是否有跟此小单的跟车用户
//        $order_gens = Db::name('order_gen')->where('orderpro_id', $order_pro_ing['id'])->where('status', 0)->select();
//        Db::startTrans();
//        try {
//            if ($order_gens) {
//                //上车
//                foreach ($order_gens as $k=>$v){
//                    //记录上车订单变化
//                    Db::name('order_gen')->where('id', $v['id'])->update([
//                        'remain_num' => 0,
//                        'status' => 1,
//                        'updatetime' => time(),
//                        'end_time' => time(),
//                    ]);
//                    //订单完成消息
//                    $content = "您的陪玩上车已完成,感谢支持";
//                    Order_news::new_add($v['user_id'], $v['id'], $v['order_sn'], 2, 0, $content);
//
//                }
//                //主播本小单金币变化上车结算
//                $gen_total_price =  Db::name('order_gen')->where('orderpro_id',$order_pro_ing['id'])->where('anchor_id',$anchor_user['id'])->sum('total_price');
//                \app\common\model\User::money($gen_total_price, $order_pro_ing['anchor_id'], 4, $order_pro_ing['id']);
//
//            }
//
//            //下单用户  订单已经完成
//            //大单子订单变化
//            Db::name('order_place')->where('id', $id)->update([
//                'status' => 2,
//                'updatetime' => time(),
//                'end_time' => time()
//            ]);
//            //小单子订单变化
//            Db::name('order_place_pro')->where('id', $anchor_user['order_ing'])->where('status', 1)->update([
//                'status' => 2,
//                'end_time' => time()
//            ]);
//            //主播本小单金币变化下单结算
//            \app\common\model\User::money($order_pro_ing['place_price'], $order_pro_ing['anchor_id'], 3, $order_pro_ing['id']);
//            //次大单还有小单子  取消订单  金币返给下单人
//            if ($remain_order_pro) {
//                $quxiao_prices = 0;
//                foreach ($remain_order_pro as $k => $v) {
//                    Db::name('order_place_pro')->where('id', $v['id'])->update([
//                        'status' => -1,
//                        'quxiao_time' => time(),
//                    ]);
//                    $quxiao_prices = $quxiao_prices + $v['place_price'];
//                }
//                \app\common\model\User::money($quxiao_prices, $place_user['user_id'], 5, $id);
//            }
//            //修改此时主播的状态
//            Db::name('user')->where('id', $place_user['anchor_id'])->update([
//                'anchor_status' => 0,
//                'order_ing' => 0,
//            ]);
//
//            //关闭主播下车按钮
//            Db::name('user')->where('id', $place_user['anchor_id'])->update(['exit_switch' => 0]);
//            Db::commit();
//        } catch (Exception $e) {
//            Db::rollback();
//            $this->error($e->getMessage(), $e->getTrace());
//        }
//        $this->success('成功');
//    }

    //用户/主播 取消待服务订单
    public function quxiao_order()
    {
        $id = $this->request->post('id');
        $order_place = Db::name('order_place')->where('id', $id)->where('status', 0)->find();
        if (empty($order_place)) {
            $this->error('订单有误');
        }

        Db::startTrans();
        try {
            Db::name('order_place')->where('id', $id)->where('status', 0)->update(['status' => -1, 'quxiao_time' => time()]);
            Db::name('order_place_pro')->where('order_id', $order_place['id'])->where('status', 0)->update([
                'status' => -1,
                'quxiao_time' => time(),
            ]);
            \app\common\model\User::money($order_place['total_price'], $order_place['user_id'], 5, $id);
            //主播取消给订单消息
            $user = $this->auth->getUser();
            if ($user['group_id'] == 1){ //主播取消 给用户发消息
                //取消待服务订单消息
                $num = $order_place['num'];
                $money = $order_place['total_price'];
                $content = "主播取消了您的待服务订单$num"."单,金币值$money"."自动返还账户";
                Order_news::new_add($order_place['user_id'], $order_place['id'], $order_place['order_sn'], 1, 0, $content);
            }else{  //用户自己取消 用户也获得消息
                //取消待服务订单消息
                $num = $order_place['num'];
                $money = $order_place['total_price'];
                $content = "您取消了自己的订单，金币自动返还账户";
                Order_news::new_add($order_place['user_id'], $order_place['id'], $order_place['order_sn'], 1, 0, $content);
            }

            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage(), $e->getTrace());
        }
        $this->success('取消订单成功');
    }

    //主播修改 设置
    public function anchor_config()
    {
        $user = $this->auth->getUser();
        if($user['up_switch'] == 1){
            $this->error('开播状态下不允许修改下单和上车金额');
        }
        if($user['anchor_status'] == 1){
            $this->error('正在进行状态下不允许修改下单和上车金额');
        }
        $order_wei = Db::name('order_place')->where('anchor_id',$user['id'])->where('status',0)->find();
        if($order_wei){
            $this->error('还有待服务的单子,不允许修改下单和上车金额');
        }

        $place_price = $this->request->post('place_price');
        $gen_price = $this->request->post('gen_price');
        $anchor_config = Anchor_config::where('anchor_id', $user['id'])->find();
        if ($anchor_config) {//更改
            if ($place_price) {
                $anchor_config->place_price = $place_price;
                $anchor_config->save();
            }
            if ($gen_price) {
                $anchor_config->gen_price = $gen_price;
                $anchor_config->save();
            }
        } else { //添加
            $anchor_config = new Anchor_config();
            $anchor_config->anchor_id = $user['id'];
            if ($place_price) {
                $anchor_config->place_price = $place_price;
            }
            if ($gen_price) {
                $anchor_config->gen_price = $gen_price;
            }
            $anchor_config->save();
        }
        $this->success('成功');
    }


    //主播修改关数奖励守护值
    public function update_custom_guard()
    {
        $user = $this->auth->getUser();
        $custom = $this->request->post('custom');
        $place_guard = $this->request->post('place_guard');
        $gen_guard = $this->request->post('gen_guard');
        $anchor_custorm = Anchor_custorm::where(['anchor_id' => $user['id'], 'custom' => $custom])->find();
        if (empty($anchor_custorm)) {
            $this->error('关数有误');
        }
        if ($place_guard) {
            $anchor_custorm->place_guard = $place_guard;
        }
        if ($gen_guard) {
            $anchor_custorm->gen_guard = $gen_guard;
        }
        $anchor_custorm->save();
        $this->success('成功');
    }
    //主播查看关数奖励守护值
    public function select_custom_guard()
    {
        $user = $this->auth->getUser();
        $custom = $this->request->post('custom');
        $anchor_custorm = Anchor_custorm::where(['anchor_id' => $user['id'], 'custom' => $custom])->find();
        if (empty($anchor_custorm)) {
            $this->error('关数有误');
        }
        $this->success('成功',$anchor_custorm);
    }
    //主播的金币记录
    public function anchor_money_log()
    {
        $user = $this->auth->getUser();
        $pagesize = $this->request->post('pagesize',10);
        $msg = "主播金币记录";
        $userMoney = MoneyLog::where('user_id',$user['id'])
            ->where('type','in',[3,4])
            ->order('createtime desc')
            ->paginate($pagesize)
            ->each(function ($v){
                if($v['type'] == 3){
                    $order_place_pro =  Db::name('order_place_pro')->where('id',$v['memo'])->find();
                    $v['num'] =$order_place_pro['num'];
                    $v['anchor_nickname'] = Db::name('user')->where('id',$order_place_pro['user_id'])->value('nickname');
                }
                elseif ($v['type'] == 4){
                    $order_gen =  Db::name('order_gen')->where('id',$v['memo'])->find();
                    $v['num'] = $order_gen['num'];
                    $v['anchor_nickname'] = Db::name('user')->where('id',$order_gen['user_id'])->value('nickname');
                }
                $v['createtime'] = date('Y-m-d H:i:s' , $v['createtime']);
                return $v;
        });
        //主播金币记录消除红点
         MoneyLog::where('user_id',$user['id'])->where('type','in',[3,4])->update(['red_status'=>1]);
        //修改主播信息
        Db::name('user')->where('id',$user['id'])->update(['moneylog_red_status'=>1]);
        $this->success($msg,$userMoney);
    }
    //主播:取消当前进行下单订单的剩余小单（结算正在进行的单子）
    public function anchor_quxiao_remain(){
        $id = $this->request->post('id');
        $place_user = Db::name('order_place')->where('id', $id)->where('status', 1)->find();
        //主播信息
        $anchor_user = Db::name('user')
            ->where(['id' => $place_user['anchor_id'], 'group_id' => 1])
            ->field('id,group_id,nickname,board_switch,exit_switch,up_switch,anchor_status,order_ing,avatar,gender')
            ->find();
        //正在进行的小单信息
        $order_pro_ing = Db::name('order_place_pro')->where('id', $anchor_user['order_ing'])->where('status', 1)->find();
        $custom_ing = $order_pro_ing['custom'];
//        if($custom_ing == 1 && $order_pro_ing['alr_custom'] == 0){
//            $custom_ing = 0;
//        }
//        if (!$place_user || !$order_pro_ing) {
//            $this->error('订单有误');
//        }
//        //结算奖励计算
//        $anchor_custom = Db::name('anchor_custorm')->where('anchor_id', $place_user['anchor_id'])->select();
//        //下单的用户
//        $place_score = 0;
//        foreach ($anchor_custom as $k => $v) {
//            if ($v['custom'] >= 1 && $v['custom'] <= $custom_ing) {
//                $place_score = $place_score + $v['place_guard'];
//            }
//        }
        //结算奖励计算(下单)
        $anchor_custom = Db::name('anchor_custorm')->where('anchor_id', $place_user['anchor_id'])->where('custom',$custom_ing)->find();
        $place_score = $anchor_custom['place_guard'];
        //是否此大单还有小单
        $remain_order_pro = Db::name('order_place_pro')->where('order_id', $id)->where('status', 0)->field('id,place_price')->select();
        //剩余订单个数
        $remain_order_pro_count = Db::name('order_place_pro')->where('order_id', $id)->where('status', 0)->field('id,place_price')->count();
        //是否有跟此小单的跟车用户
        $order_gens = Db::name('order_gen')->where('orderpro_id', $order_pro_ing['id'])->where('status', 0)->select();
        Db::startTrans();
        try {
            if ($order_gens) {
                //跟单所有用户结算  （因为user_exit方法里有判断下单订单状态  所以给放到前面处理）
                foreach ($order_gens as $k => $v) {
                    $return = $this->user_exit($v['user_id'], $v['id'], $v['remain_num']);
                }
            }

            //下单用户  订单已经完成
            //大单子订单变化
            Db::name('order_place')->where('id', $id)->update([
                'status' => 2,
                'place_guard' => $place_user['place_guard'] + $place_score,
                'updatetime' => time(),
                'end_time' => time()
            ]);
            //小单子订单变化
            Db::name('order_place_pro')->where('id', $anchor_user['order_ing'])->where('status', 1)->update([
                'place_guard' => $place_score,
                'status' => 2,
                'end_time' => time()
            ]);
            //用户守护值
            \app\common\model\User::score($place_score, $place_user['user_id'], 1, $order_pro_ing['id'],$place_user['anchor_id'] );
            //主播本小单金币变化下单结算
            \app\common\model\User::money($order_pro_ing['place_price'], $order_pro_ing['anchor_id'], 3, $order_pro_ing['id']);
            //次大单还有小单子  取消订单  金币返给下单人
            if ($remain_order_pro) {
                $quxiao_prices = 0;
                foreach ($remain_order_pro as $k => $v) {
                    Db::name('order_place_pro')->where('id', $v['id'])->update([
                        'status' => -1,
                        'quxiao_time' => time(),
                    ]);
                    $quxiao_prices = $quxiao_prices + $v['place_price'];
                }
                \app\common\model\User::money($quxiao_prices, $place_user['user_id'], 5, $id);
                //取消剩余订单消息
                $content = "主播取消了你的剩余订单$remain_order_pro_count"."单,金币值$quxiao_prices"."自动返还账户";
                Order_news::new_add($place_user['user_id'], $place_user['id'], $place_user['order_sn'], 1, 0, $content);
            }
            //修改此时主播的状态
            Db::name('user')->where('id', $place_user['anchor_id'])->update([
                'anchor_status' => 0,
                'order_ing' => 0,
            ]);
            //关闭主播下车按钮
            Db::name('user')->where('id', $place_user['anchor_id'])->update(['exit_switch' => 0]);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage(), $e->getTrace());
        }
        $this->success('成功');
    }
    //主播点击完成/进行下一单结算（结算本小单）
    public function next_order()
    {
        $user = $this->auth->getUser();
        $user_id = $user['id'];
        $id = $this->request->post('id');
        $place_user = Db::name('order_place')->where('id', $id)->where('status', 1)->find();
        //主播信息
        $anchor_user = Db::name('user')
            ->where(['id' => $place_user['anchor_id'], 'group_id' => 1])
            ->field('id,group_id,nickname,board_switch,exit_switch,up_switch,anchor_status,order_ing,avatar,gender')
            ->find();
        //正在进行的小单信息
        $order_pro_ing = Db::name('order_place_pro')->where('id', $anchor_user['order_ing'])->where('status', 1)->find();
        $custom_ing = $order_pro_ing['custom'];
//        if($custom_ing == 1 && $order_pro_ing['alr_custom'] == 0){
//            $custom_ing = 0;
//        }
        if (!$place_user || !$order_pro_ing) {
            $this->error('订单有误');
        }
        //结算奖励计算(下单)
        $anchor_custom = Db::name('anchor_custorm')->where('anchor_id', $place_user['anchor_id'])->where('custom',$custom_ing)->find();
        $place_score = $anchor_custom['place_guard'];

        //是否有跟此小单的跟车用户
        $order_gens = Db::name('order_gen')->where('orderpro_id', $order_pro_ing['id'])->where('status', 0)->select();
        //是否此大单还有小单
        $remain_order_pro = Db::name('order_place_pro')->where('order_id', $id)->where('status', 0)->field('id,place_price')->select();
        Db::startTrans();
        try {
            //跟单所有用户结算  （因为user_exit方法里有判断下单订单状态  所以给放到前面处理）
            if ($order_gens) {
                foreach ($order_gens as $k => $v) {
                    $return = $this->user_exit($v['user_id'], $v['id'], $v['remain_num']);
                }
            }

            //下单用户  订单已经完成
            //大单子订单变化
            if ($remain_order_pro) {//进行下一单
                Db::name('order_place')->where('id', $id)->update([
                    'alr_num' => $place_user['alr_num'] + 1,
                    'place_guard' => $place_user['place_guard'] + $place_score,
                    'updatetime' => time(),
                    'end_time' => time()
                ]);

            } else { //完成订单

                Db::name('order_place')->where('id', $id)->update([
                    'status' => 2,
                    'place_guard' => $place_user['place_guard'] + $place_score,
                    'updatetime' => time(),
                    'end_time' => time()
                ]);
                //订单完成消息(用户)
                $content = "您的下单订单已完成,感谢支持";
                Order_news::new_add($place_user['user_id'], $place_user['id'], $place_user['order_sn'], 1, 0, $content);

            }

            //小单子订单变化
            Db::name('order_place_pro')->where('id', $anchor_user['order_ing'])->where('status', 1)->update([
                'place_guard' => $place_score,
                'status' => 2,
                'end_time' => time()
            ]);
            //用户守护值
            \app\common\model\User::score($place_score, $place_user['user_id'], 1, $order_pro_ing['id'],$place_user['anchor_id']);
            //主播本小单金币变化下单结算
            \app\common\model\User::money($order_pro_ing['place_price'], $order_pro_ing['anchor_id'], 3, $order_pro_ing['id']);
            //此大单还有小单子
            if ($remain_order_pro) {// 进行下一小单子
                $next_order_pro = Db::name('order_place_pro')->where('order_id', $id)->where('status', 0)->find();
                //修改此时主播的状态
                Db::name('user')->where('id', $place_user['anchor_id'])->update([
                    'anchor_status' => 1,
                    'order_ing' => $next_order_pro['id'],
                ]);
                Db::name('order_place_pro')->where('id', $next_order_pro['id'])->update([
                    'status' => 1,
                    'begin_time' => time(),
                ]);
            } else { //已完成订单
                //修改此时主播的状态
                Db::name('user')->where('id', $place_user['anchor_id'])->update([
                    'anchor_status' => 0,
                    'order_ing' => 0,
                ]);
                //订单完成消息(主播)
                $content = "您的下单订单已完成,感谢支持";
                Order_news::new_add($place_user['anchor_id'], $place_user['id'], $place_user['order_sn'], 1, 1, $content);
            }
            //关闭主播下车按钮
            Db::name('user')->where('id', $place_user['anchor_id'])->update(['exit_switch' => 0]);

            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage(), $e->getTrace());
        }
        $this->success('成功');
    }
    //获取主播的最新按钮状态
    public function get_anchor_status(){
        $anchor_id = $this->request->post('id');
        $anchor_user = Db::name('user')
            ->where('id',$anchor_id)
            ->where('group_id',1)
            ->field('id,anchor_status,order_ing,board_switch,exit_switch,up_switch')
            ->find();
        $this->success('成功',$anchor_user);
    }
    //主播关数奖励页面列表
    public function anchor_award(){
        $user = $this->auth->getUser();
        $anchor_custorm = Db::name('anchor_custorm')
            ->where('anchor_id',$user['id'])
            ->select();
        $this->success('成功',$anchor_custorm);
    }
}